package com.xy.iot.client.config;
import com.xy.iot.client.config.properties.IotNettyClientProperties;
import com.xy.iot.common.enums.CommandEnum;
import com.xy.iot.common.result.message.JSONMessageData;
import com.xy.iot.netty.StartClient;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;

/**
 * iot 客户端服务启动配置
 */
@Slf4j
@Configuration
public class IotServerConfig implements ApplicationRunner {
	@Getter
	private static StartClient startClient = null;
	@Autowired
	private IotNettyClientProperties iotNettyClientProperties;
	/**
	 * spring boot启动调用，启动 netty 服务
	 * @param args
	 * @throws Exception
	 */
	@Override
    public void run(ApplicationArguments args) throws Exception {

		if (iotNettyClientProperties.getOpen()){
			startClient = new StartClient(iotNettyClientProperties.getDeviceGroup(), iotNettyClientProperties.getThread(), iotNettyClientProperties.getHeartBeatTime(), JSONMessageData.class);
			startClient.addListener(CommandEnum.SERVER_PING.getKey(), (channel, message) -> {
				log.info("收到服务端心跳返回：{}",message);
			});
		}
		if (startClient!=null){
			String[] ips = iotNettyClientProperties.getIps().split(",");
			for (String ip : ips) {
				startClient.connect(ip, iotNettyClientProperties.getPort(), iotNettyClientProperties.getReconnectTime());
			}
		}
	}

	/**
	 * spring boot 进程停止事件，关闭  netty 服务
	 * @param event
	 */
	@EventListener
	public void handleMyEvent(ContextClosedEvent event) {
		if (startClient!=null){
			String[] ips = iotNettyClientProperties.getIps().split(",");
			for (String ip : ips) {
				startClient.stop(ip);
			}
		}
	}

}
